package h_10_26;

import java.util.HashMap;

/**
 * 2958. 最多 K 个重复元素的最长子数组
 * https://leetcode.cn/problems/length-of-longest-subarray-with-at-most-k-frequency/description/
 */
public class Main4 {
    public int maxSubarrayLength(int[] nums, int k) {
        HashMap<Integer,Integer> hash = new HashMap<>();
        int n = nums.length;
        int left = 0;
        int right = 0;
        int ret = 0;
        while(right < n) {
            int in = nums[right];
            hash.put(in,hash.getOrDefault(in,0) + 1);

            while(hash.get(in) > k) {
                int out = nums[left];
                hash.put(out,hash.get(out) - 1);
                left++;
            }

            ret = Math.max(ret,right - left + 1);
            right++;
        }
        return ret;
    }
}
